﻿#include "canthread.h"
#include "ControlCAN.h"

#include <QLibrary>
#include <QDebug>
#include <QThread>

const DWORD GCanBrTab[10] = {
    0x060003, 0x060004, 0x060007,
    0x1C0008, 0x1C0011, 0x160023,
    0x1C002C, 0x1600B3, 0x1C00E0,
    0x1C01C1
};

CanThread::CanThread(QObject *parent) : QObject(parent)
{
    m_isLoad = true;

    pThread = new QThread();
    pTimer = new QTimer();
    pTimer->setInterval(100);

    this->moveToThread(pThread);
    pTimer->moveToThread(pThread);
    pCanLib->moveToThread(pThread);

    connect(pTimer, &QTimer::timeout, this, &CanThread::SlotTimer);

    pThread->start();
}

CanThread::~CanThread()
{
    if(m_isLoad) {
        pTimer->stop();
        if(pThread) {
            pThread->quit();
            pThread->wait();
        }

        delete pTimer;
        delete pThread;
    }
}

CanThread* CanThread::Instance()
{
    static CanThread thread;

    return &thread;
}

bool CanThread::isLoad()
{
    return m_isLoad;
}

bool CanThread::isOpen()
{
    return m_isOpen;
}

bool CanThread::isConnect()
{
    return m_isConnect;
}

void CanThread::SlotCanConnect(unsigned long type, unsigned long baudrateIndex)
{
    qDebug() << "open can type:" << type;

    if(m_isOpen) {
        VCI_CloseDevice(devtype, 0);
        m_isOpen = false;
        return;
    }

    VCI_INIT_CONFIG init_config;
    type = (type == 1) ? 21 : 20;
    if(baudrateIndex > 9) baudrateIndex = 3;
    DWORD baudrate = GCanBrTab[baudrateIndex];

    devtype = type;
    init_config.Mode=0;

    unsigned ret = VCI_OpenDevice(devtype, 0, 0);

    if(ret != STATUS_OK) {
        qDebug() << "open can failed type:" << type;
        return;
    }
    if (VCI_SetReference(devtype, 0, 0, 0, &baudrate) != STATUS_OK) {
        qDebug() << "SetReference can failed";
        VCI_CloseDevice(devtype,0);
        return;
    }
    if(VCI_InitCAN(devtype, 0, 0, &init_config) != STATUS_OK) {
        qDebug() << "init can failed";
        VCI_CloseDevice(devtype, 0);
        return;
    }

    m_isOpen = true;
}

void CanThread::SlotCanStart()
{
    if(m_isOpen) {
        if(!m_isConnect)
            m_isConnect = (VCI_StartCAN(devtype, 0, 0) == 1);
    }
}

void CanThread::SlotCanRestart()
{
    if(m_isOpen) {
        if(m_isConnect)
            m_isConnect = (VCI_ResetCAN(devtype, 0, 0) == 1);
    }
}

void CanThread::SlotCanStop()
{
    VCI_CloseDevice(devtype, 0);
    m_isConnect = false;
    m_isOpen = false;
}

void CanThread::SlotTimer()
{
    if(m_isOpen && m_isConnect) {

    }
}
